package com.imooc.bilibili.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.imooc.bilibili.auth.IAuthRoleService;
import com.imooc.bilibili.auth.IUserRoleService;
import com.imooc.bilibili.auth.UserAuthService;
import com.imooc.bilibili.constant.auth.AuthRoleConstant;
import com.imooc.bilibili.domain.auth.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author gcq
 * @Create 2022-05-31
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IAuthRoleService authRoleService;

    @Override
    public UserAuthorities getUserAuthorities(Long userId) {
        List<UserRole> userRoleList = userRoleService.getUserRoleByUserId(userId);
        Set<Long> roleIdSet = userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        List<AuthRoleElementOperation> roleElementOperationList = authRoleService.getRoleElementOperationByRoleIds(roleIdSet);
        List<AuthRoleMenu> roleMenuList = authRoleService.getAuthRoleMenuByRoleIds(roleIdSet);
        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleMenuList(roleMenuList);
        userAuthorities.setRoleElementOperationList(roleElementOperationList);
        return userAuthorities;
    }

    @Override
    public void addUserDefaultRole(Long id) {
        UserRole userRole = new UserRole();
        AuthRole role = authRoleService.getOne(new QueryWrapper<AuthRole>().eq("code", AuthRoleConstant.ROLE_LV0));
        userRole.setUserId(id);
        userRole.setRoleId(role.getId());
        userRole.setCreateTime(new Date());
        userRoleService.save(userRole);
    }

}